import { _decorator, Vec3, Node,tween,v3 } from 'cc';
import { Room } from './room';
import { Util } from './util';
const { ccclass, property } = _decorator;

@ccclass('Prg')
export class Prg  {
    static speed = 300

    node: Node
    startPositon: Vec3
    randomEndPostion: Vec3
    targetRoom:Room = null
    enterMainPostion: Vec3

    path: Array<Vec3>
    moving:boolean = false

    userId:number
    userName:string
    accountBalance:number

    waiting:boolean = true

    public constructor(node: Node) {
        this.node = node;
        this.startPositon = this.node.getPosition()
    }

    setEnterMainPostion(enterMainPostion:Vec3) {
        this.enterMainPostion = enterMainPostion
    }

    setTargetRoom(targetRoom:Room) {
        this.targetRoom = targetRoom;
        this.randomEndPostion = this.targetRoom.getRandomEndPostion()
        this.path = [this.startPositon, this.enterMainPostion, ...this.targetRoom.path, this.targetRoom.getRandomEndPostion()]
    }

    changeTargetRoom(targetRoom:Room) {
        this.setTargetRoom(targetRoom)
        this.node.setPosition(this.randomEndPostion)
    }

    target() {
        //console.log(this.userId, this.randomEndPostion)
        //console.log(this.randomEndPostion)
        this.node.setPosition(this.randomEndPostion)
    }

    move() {
        this.moving = true
        let t = tween(this.node)

        let start = this.path[0]
        for (let p of this.path) {
            let duration = Util.getDistance(start, p) / Prg.speed
            t.to(duration, { position: p})
            start = p
        }

         t.call(() => { this.moving = false })
        .start()        
    }

    back(func:() => void) {

        let t = tween(this.node)
        let path = this.path.reverse()
        let start = path[0]
        for (let p of path) {
            let duration = Util.getDistance(start, p) / Prg.speed
            t.to(duration, { position: p})
            start = p
        }

         t.call(func)
        .start()        
    }

}

